package h;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import b.User;


@SuppressWarnings("serial")
public class AuthorizationServlet extends HttpServlet {

	public void doPost(HttpServletRequest request,HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String prevpage = request.getParameter("prevpage");

		try {
			User u = User.authorizate(username, password);
			if(u==null) {
				try {
					response.sendRedirect(String.format("%s/login.html?prevpage=%s",
							request.getContextPath(),
							prevpage.replaceAll("&","%26")));
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				RequestContext rc;
				if((rc = (RequestContext)request.getSession().getAttribute("Request-Context"))==null) {
					rc = new RequestContext();
					rc.setCurrentUser(u);
					request.getSession().setAttribute("Request-Context",rc);
				}
				
				request.getSession().setAttribute("Request-Context", rc);
				response.sendRedirect(prevpage==null?request.getContextPath():prevpage);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doGet(HttpServletRequest request,HttpServletResponse respone) {
		doPost(request,respone);
	}
}
